<template>
  <div>
    <el-dialog :title="dialogStatus=='create'? '新增审核单':'修改审批单'" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="90%">
      <el-form
        ref="dataDetailForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="110px"
      >
        <!-- <el-form-item label="ID" prop="id"><el-input v-model="temp.id" :readonly="dialogStatus==='update'"/></el-form-item> -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="审批单编号" prop="orderCode">
              <el-input v-model="temp.orderCode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="comment">
              <el-input v-model="temp.comment" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="审批单日期" prop="orderDate">
              <el-date-picker
                v-model="temp.orderDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              />
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="总价" prop="price">
              {{ totalPrice }} 元
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row>
        <el-button type="primary" class="filter-item" @click="addMaterialDetail()">+</el-button>
        <el-button type="primary" class="filter-item" style="float: right;" :disabled="this.canNotMerge" @click="splitCell()">拆分单元格</el-button>
        <el-button type="primary" class="filter-item" style="float: right;" :disabled="this.canNotMerge" @click="mergeCell()">合并单元格</el-button>
      </el-row>
      <el-table
        :data="orderDetail"
        :cell-class-name="cellRowClassName"
        :span-method="arraySpanMethod"
        border
        style="width: 100%;margin-top: 10px;"
        height="450"
        :row-style="{height: '100px'}"
        @cell-click="cellSelect"
      >
        <el-table-column label="序号" type="index" />
        <el-table-column prop="materialCode" label="设备编码" align="center" width="140px">
          <template slot-scope="scope">
            <div @click.stop="">
              <el-autocomplete
                v-model="scope.row.materialCode"
                :trigger-on-focus="false"
                class="inline-input"
                :fetch-suggestions="queryMaterial('materialCode','materialName')"
                type="textarea"
                :autosize="{ minRows: 3, maxRows: 6 }"
                @input="change($event)"
                @select="((item) => {handleMaterialSelect(item, scope.row)})"
              >
                <template slot-scope="{ item }">
                  <div class="name">{{ item.value }}</div>
                  <span class="addr">{{ item.desc }}</span>
                </template>
              </el-autocomplete>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="materialName" label="设备名称" align="center" width="200px">
          <template slot-scope="scope">
            <div @click.stop="">
              <el-autocomplete
                v-model="scope.row.materialName"
                :trigger-on-focus="false"
                class="inline-input"
                :fetch-suggestions="queryMaterial('materialName', 'materialSpecification')"
                type="textarea"
                :autosize="{ minRows: 3, maxRows: 6 }"
                @input="change($event)"
                @select="((item) => {handleMaterialSelect(item, scope.row.idx)})"
              >
                <template slot-scope="{ item }">
                  <div class="name"><a :title="item.value" style="text-decoration:none">{{ item.value }}</a></div>
                  <span class="addr">{{ item.desc }}</span>
                </template>
              </el-autocomplete>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="materialSpecification" label="规格" align="center" width="200px">
          <template slot-scope="scope">
            <div @click.stop="">
              <el-autocomplete
                      v-model="scope.row.materialSpecification"
                      :trigger-on-focus="false"
                      class="inline-input"
                      :fetch-suggestions="queryMaterial('materialSpecification', 'materialName')"
                      type="textarea"
                      :autosize="{ minRows: 3, maxRows: 6 }"
                      @input="change($event)"
                      @select="((item) => {handleMaterialSelect(item, scope.row.idx)})"
              >
                <template slot-scope="{ item }">
                  <div class="name"><a :title="item.value" style="text-decoration:none">{{ item.value }}</a></div>
                  <span class="addr">{{ item.desc }}</span>
                </template>
              </el-autocomplete>
            </div>
            <!--<div @click.stop="">-->
              <!--<el-input-->
                <!--v-model="scope.row.materialSpecification"-->
                <!--type="textarea"-->
                <!--:autosize="{ minRows: 3, maxRows: 6 }"-->
                <!--@input="change($event)"-->
              <!--/>-->
            <!--</div>-->
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" align="center" width="100px">
          <template slot-scope="scope">
            <div @click.stop="">
              <el-input
                v-model="scope.row.unit"
                type="text"
                @input="change($event)"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="materialNum" label="数量" align="center" width="100px">
          <template slot-scope="scope">
            <div @click.stop="">
              <el-input
                v-model="scope.row.materialNum"
                type="number"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="单价（元）" align="center" width="100px">
          <template slot-scope="scope">
            <div @click.stop="">
              <el-input v-model="scope.row.unitPrice" @input="change($event)" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="materialTotalPrice" label="总价（元）" align="center" width="80px">
          <template slot-scope="scope">
            <p>{{ (scope.row.unitPrice * scope.row.materialNum ).toFixed(2) }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="projectName" label="项目（用途）" align="center" width="150px">
          <template slot-scope="scope">
            <div @click.stop="">
              <el-autocomplete
                      v-model="scope.row.projectName"
                      :trigger-on-focus="false"
                      class="inline-input"
                      :fetch-suggestions="queryProject()"
                      type="textarea"
                      :autosize="{ minRows: 3, maxRows: 6 }"
                      @input="change($event)"
              >
                  <template slot-scope="{item}">
                      <el-tooltip :content="item.value" placement="right" effect="light">
                          <div style="overflow:hidden">{{item.value}}</div>
                      </el-tooltip>
                  </template>
              </el-autocomplete>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="indentCode" label="采购订单编号" align="center" width="150px">
          <template slot-scope="scope">
            <div @click.stop="">
              <el-input v-model="scope.row.indentCode" type="textarea" />
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="this.dialogStatus === 'update'" prop="contractCode" label="合同编号" align="center" width="150px">
          <template slot-scope="scope">
            <div @click.stop="">
              <el-input v-model="scope.row.contractCode" type="textarea" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="supplierName" label="供应商" align="center" width="200px">
          <template slot-scope="scope">
            <div @click.stop="">
              <el-autocomplete
                v-model="scope.row.supplierName"
                :trigger-on-focus="false"
                class="inline-input"
                :fetch-suggestions="querySupplier()"
                type="textarea"
                :autosize="{ minRows: 3, maxRows: 6 }"
                @input="change($event)"
              >
                <!--<template slot-scope="{ item }">-->
                <!--<div class="name">{{ item.value }}</div>-->
                <!--<span class="addr">{{ item.desc }}</span>-->
                <!--</template>-->
              </el-autocomplete>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="50px">
          <template slot-scope="{row, index}">
            <el-popconfirm
              title="确定删除吗？"
              @confirm="removeMaterial(row, index)"
            >
              <el-button
                slot="reference"
                style="margin-left: 5px"
                type="text"
                divided
              >删除
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="cancleDetail">取消</el-button>
        <el-button icon="el-icon-check" type="primary" @click="addOrUpdateOrder()">确定
        </el-button>
      </div>
    </el-dialog>
  </div>

</template>
<style>
  .name {
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .addr {
    font-size: 12px;
    color: #b4b4b4;
  }
  .el-table .warning-row {
    background: oldlace !important;
  }

  .el-table .success-row {
    background: #f0f9eb !important;
  }
</style>
<script>
import { putAction, getAction, postAction } from '@/api/manage'
import { Message } from 'element-ui'

export default {
  name: '',
  components: {
  },
  props: {
    dialogStatus: {
      type: String,
      default: 'create'
    }
  },
  data() {
    return {
      dialogFormVisible: false,
      temp: {
        id: undefined,
        orderCode: '',
        orderName: '',
        orderDate: this.getCurDate(),
        price: '',
        orderUsage: '',
        comment: '',
        orderState: '',
        attachmentNum: ''
      },
      orderDetail: [],
      rules: {
        orderCode: [{ required: true, message: '审批单编码不能为空', trigger: 'change' }],
        orderDate: [{ required: true, message: '日期不能为空', trigger: 'change' }]
      },
      orderCodeArr: undefined,
      projectNameArr: undefined,
      indentCodeArr: undefined,
      supplierNameArr: undefined,
      selectCells: [],
      selectCellObj: [],
      mergedCell: [],
      materials: [],
      suppliers: [],
      projects: [],
      columnPropMap: {}
    }
  },
  computed: {
    // 计算属性的 getter
    canNotMerge: function() {
      return this.selectCellObj.length === 0
    },
    totalPrice: function() {
      // `this` 指向 vm 实例
      var total = 0
      this.orderDetail.forEach((e) => {
        total += e.unitPrice * e.materialNum
      })
      return total
    }
  },
  created() {
  },
  mounted() {
    this.getMaterialAll()
    this.getSupplierAll()
    this.getProjectAll()
  },

  methods: {
    // disposeOrderDetail() {
    //   if (this.orderDetail.length > 0 && this.mergedCell.length > 0) {
    //     for (var i = 0; i < this.mergedCell.length; i++) {
    //       for (var j = this.mergedCell[i][0]; j <= this.mergedCell[i][2]; j++) {
    //         for (var k = this.mergedCell[i][1]; k < this.mergedCell[i][3]; k++) {
    //             if (j === this.mergedCell[i][0] &&  k === this.mergedCell[i][1]) {
    //
    //             }else {
    //               this.orderDetail[j][]
    //             }
    //         }
    //       }
    //     }
    //   }
    // },
    addOrUpdateOrder() {
      this.$refs['dataDetailForm'].validate((valid) => {
        if (valid) {
          // 校验orderDetail
          if (this.orderDetail.length === 0) {
            Message.error('审批单内容不能为空')
            return
          } else {
            var that = this
            var checkPass = true
            this.orderDetail.forEach(function(e) {
              if (that.isEmpty(e.materialName) || that.isEmpty(e.materialNum) ||
                that.isEmpty(e.supplierName) || that.isEmpty(e.indentCode) ||
                that.isEmpty(e.unitPrice) || that.isEmpty(e.projectName)) {
                checkPass = false
              }
            })
            if (!checkPass) {
              Message.error('详情项不能为空（设备名称，数量，单价，项目，订单号，供应商）')
              return
            }
          }
          this.temp.details = this.orderDetail
          // this.temp.price = this.totalPrice
          postAction('/purchase/order/save', this.temp).then((res) => {
            if (res.code === 200) {
              // 成功
              this.dialogFormVisible = false
              this.$emit('handleChild', { type: 'orderUpdated' })
            }

            Message.success(res.msg)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    addMaterialDetail() {
      this.orderDetail.push({ materialCode: '', materialName: '', materialSpecification: '', unit: '', materialNum: null, unitPrice: null, materialTotalPrice: null, projectName: '', indentCode: '', supplierName: '' })
    },
    removeMaterial(row, index) {
      this.removeObjWithArr(this.orderDetail, row)
    },
    queryMaterial(prop, descProp) {
      return (queryString, cb) => {
        var materialFilters = []
        this.materials.forEach(function(item) {
          if (item[prop] !== null && item[prop] !== undefined) {
            materialFilters.push({ 'value': item[prop], 'desc': item[descProp], 'obj': item })
          }
        })
        // 根据val做一些事情
        var results = queryString ? materialFilters.filter(this.createFilter(queryString)) : materialFilters
        cb(results)
      }
    },
    querySupplier() {
      return (queryString, cb) => {
        var supplierFilters = []
        this.suppliers.forEach(function(item) {
          if (item['supplierName'] !== null && item['supplierName'] !== undefined) {
            supplierFilters.push({ 'value': item['supplierName'] })
          }
        })
        // 根据val做一些事情
        var results = queryString ? supplierFilters.filter(this.createFilter(queryString)) : supplierFilters
        cb(results)
      }
    },
    queryProject() {
      return (queryString, cb) => {
        var projectFilters = []
        this.projects.forEach(function(item) {
          if (item['projectName'] !== null && item['projectName'] !== undefined) {
            projectFilters.push({ 'value': item['projectName'] })
          }
        })
        // 根据val做一些事情
        var results = queryString ? projectFilters.filter(this.createFilter(queryString)) : projectFilters
        cb(results)
      }
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) >= 0)
      }
    },

    handleMaterialSelect(item, idx) {
      ['materialCode', 'materialName', 'materialSpecification', 'unit', 'unitPrice'].forEach(f => this.replaceField(idx, item.obj, f))
    },
    replaceNullField(idx, obj, field) {
      var row = this.orderDetail[idx]
      if (row[field] === null || row[field] === undefined || row[field] === '') {
        row[field] = obj[field]
      }
    },
    replaceField(idx, obj, field) {
      var row = this.orderDetail[idx]
      row[field] = obj[field]
    },
    getMaterialAll() {
      getAction('/purchase/material/listAll').then(
        res => {
          const { data } = res
          this.materials = data
        }
      )
    },
    getProjectAll() {
      getAction('/purchase/project/listAll').then(
        res => {
          const { data } = res
          this.projects = data
        }
      )
    },
    getSupplierAll() {
      getAction('/purchase/supplier/listAll').then(
        res => {
          const { data } = res
          this.suppliers = data
        }
      )
    },
    show(order, orderDetail) {
      this.temp = order
      this.orderDetail = orderDetail
      // 清除原先的merge
      this.mergedCell = []
      if (this.orderDetail.length > 0) {
        this.defaultMerage()
      }
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.dataDetailForm.clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const param = Object.assign({}, this.temp)
          param.payments = this.payments
          putAction('/purchase/contract/update', param).then(({ msg }) => {
            this.dialogFormVisible = false
            Message.success(msg)
            this.$emit('handleChild', { type: 'contractUpdated' })
          })
        }
      })
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (this.mergedCell.length > 0) {
        for (var i = 0; i < this.mergedCell.length; i++) {
          if (rowIndex >= this.mergedCell[i][0] && rowIndex <= this.mergedCell[i][2] &&
            columnIndex >= this.mergedCell[i][1] && columnIndex <= this.mergedCell[i][3]) {
            if (rowIndex === this.mergedCell[i][0] && columnIndex === this.mergedCell[i][1]) {
              return {
                rowspan: this.mergedCell[i][2] - this.mergedCell[i][0] + 1,
                colspan: this.mergedCell[i][3] - this.mergedCell[i][1] + 1
              }
            } else {
              var copyValue = this.orderDetail[this.mergedCell[i][0]][this.columnPropMap[this.mergedCell[i][1]]]
              this.orderDetail[rowIndex][this.columnPropMap[columnIndex]] = copyValue
              return {
                rowspan: 0,
                colspan: 0
              }
            }
          }
        }
      }
    },
    defaultMerage() {
      // 清除原先的merge
      this.mergedCell = []
      var indentCodeArr = []
      var contractCodeArr = []
      var projectNameArr = []
      var supplierNameArr = []
      let projectPos = 0
      let supplierPos = 0
      let indentPos = 0
      let contractPos = 0

      for (let i = 0; i < this.orderDetail.length; i++) {
        if (i === 0) {
          projectNameArr.push(1)
          supplierNameArr.push(1)
          indentCodeArr.push(1)
          contractCodeArr.push(1)
        } else {
          if (this.orderDetail[i].projectName === this.orderDetail[i - 1].projectName) {
            projectNameArr[projectPos] += 1
            projectNameArr.push(0)
          } else {
            projectNameArr.push(1)
            projectPos = i
          }
          if (this.orderDetail[i].supplierName === this.orderDetail[i - 1].supplierName) {
            supplierNameArr[supplierPos] += 1
            supplierNameArr.push(0)
          } else {
            supplierNameArr.push(1)
            supplierPos = i
          }

          if (this.orderDetail[i].indentCode === this.orderDetail[i - 1].indentCode) {
            indentCodeArr[indentPos] += 1
            indentCodeArr.push(0)
          } else {
            indentCodeArr.push(1)
            indentPos = i
          }
          if (this.orderDetail[i].contractCode === this.orderDetail[i - 1].contractCode) {
            contractCodeArr[contractPos] += 1
            contractCodeArr.push(0)
          } else {
            contractCodeArr.push(1)
            contractPos = i
          }
        }
      }
      for (var j = 0; j < indentCodeArr.length; j++) {
        if (indentCodeArr[j] > 1) {
          this.addMergedCell([j, 9, j + indentCodeArr[j] - 1, 9])
        }
        if (contractCodeArr[j] > 1) {
          this.addMergedCell([j, 10, j + contractCodeArr[j] - 1, 10])
        }
        if (projectNameArr[j] > 1) {
          this.addMergedCell([j, 8, j + projectNameArr[j] - 1, 8])
        }

        if (supplierNameArr[j] > 1) {
          this.addMergedCell([j, 11, j + supplierNameArr[j] - 1, 11])
        }
      }
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (column.property !== 'materialTotalPrice') {
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          if (sums[index].toString().indexOf('.') > 1) {
            sums[index] = sums[index].toFixed(2)
          }
          // sums[index] += ' 元'
        }
      })

      return sums
    },
    cellSelect(row, column, cell, event) {
      // 跳过不可合并的单元格
      if (column.property !== 'projectName' && column.property !== 'indentCode' && column.property !== 'contractCode' && column.property !== 'supplierName') {
        return
      }
      if (this.selectCells[column.idx] === null || this.selectCells[column.idx] === undefined || this.selectCells[column.idx].length === 0) {
        this.selectCells[column.idx] = [row.idx]
        cell.setAttribute('style', 'background-color: #f0f9eb !important')
        this.selectCellObj.push(cell)
      } else {
        const posIdx = this.selectCells[column.idx].indexOf(row.idx)
        if (posIdx < 0) {
          this.selectCells[column.idx].push(row.idx)
          cell.setAttribute('style', 'background-color: #f0f9eb !important')
          this.selectCellObj.push(cell)
        } else {
          cell.removeAttribute('style')
          this.selectCells[column.idx].splice(posIdx, 1)
          this.removeObjWithArr(this.selectCellObj, cell)
        }
      }
    },
    cellRowClassName({ row, column, rowIndex, columnIndex }) {
      row.idx = rowIndex
      column.idx = columnIndex
      this.columnPropMap[columnIndex] = column.property
      return ''
    },
    mergeCell() {
      if (this.selectCells.length > 0) {
        var colNum = 0
        var minCol = 0
        var maxCol = 0
        var minRow = 100
        var maxRow = 0
        for (var col = 0; col < this.selectCells.length; col++) {
          if (this.selectCells[col] !== undefined && this.selectCells[col].length > 0) {
            if (colNum === 0) {
              minCol = col
            }
            if (col > maxCol) {
              maxCol = col
            }

            var mar = Math.max(... this.selectCells[col])
            var mir = Math.min(... this.selectCells[col])
            if (mar > maxRow) {
              maxRow = mar
            }
            if (mir < minRow) {
              minRow = mir
            }
            colNum += 1
          }
        }
        console.log('最小列：' + minCol)
        console.log(maxCol)
        console.log(maxRow)
        console.log('最小行：' + minRow)
        console.log('列数：' + colNum)
        // if (colNum > 1) {
        //   console.log('err')
        // }
        if (colNum > 1) {
          Message.error('合并单元格只能在同一列内合并')
        } else {
          this.clearSelectCellStyle()
          if (!(minRow === maxRow && minCol === maxCol)) {
            this.addMergedCell([minRow, minCol, maxRow, maxCol])
          }
          this.selectCells = []
        }
      }
    },
    clearSelectCellStyle() {
      if (this.selectCellObj.length > 0) {
        for (var i = 0; i < this.selectCellObj.length; i++) {
          this.selectCellObj[i].removeAttribute('style')
        }
        this.selectCellObj = []
      }
    },
    change() {
      this.$forceUpdate()
    },
    splitCell() {
      this.clearSelectCellStyle()
      if (this.selectCells.length > 0 && this.mergedCell.length > 0) {
        var needSplit = []
        for (let k = 0; k < this.mergedCell.length; k++) {
          var finded = false
          for (let i = 0; i < this.selectCells.length; i++) {
            if (finded) {
              break
            }
            if (this.selectCells[i] !== undefined && this.selectCells[i].length > 0) {
              for (let j = 0; j < this.selectCells[i].length; j++) {
                if (finded) {
                  break
                }
                if (this.mergedCell[k][0] <= this.selectCells[i][j] &&
                   this.mergedCell[k][2] >= this.selectCells[i][j] &&
                   this.mergedCell[k][1] <= i &&
                   this.mergedCell[k][3] >= i) {
                  needSplit.push(this.mergedCell[k])
                  finded = true
                }
              }
            }
          }
        }
        if (needSplit.length > 0) {
          for (let i = 0; i < needSplit.length; i++) {
            for (let j = 0; j < this.mergedCell.length; j++) {
              if (needSplit[i][0] === this.mergedCell[j][0] &&
              needSplit[i][1] === this.mergedCell[j][1] &&
              needSplit[i][2] === this.mergedCell[j][2] &&
              needSplit[i][3] === this.mergedCell[j][3]) {
                this.mergedCell.splice(j, 1)
                break
              }
            }
          }
        }
      }
      this.selectCells = []
    },
    addMergedCell([minRow, minCol, maxRow, maxCol]) {
      if (this.mergedCell.length > 0) {
        var coincideRect = []
        var nonCoincideRect = []
        for (var i = 0; i < this.mergedCell.length; i++) {
          if (!(maxRow < this.mergedCell[i][0] || maxCol < this.mergedCell[i][1] || this.mergedCell[i][2] < minRow || this.mergedCell[i][3] < minCol)) {
            coincideRect.push(this.mergedCell[i])
          } else {
            nonCoincideRect.push(this.mergedCell[i])
          }
        }
        if (coincideRect.length > 0) {
          for (var j = 0; j < coincideRect.length; j++) {
            if (coincideRect[j][0] < minRow) {
              minRow = coincideRect[j][0]
            }
            if (coincideRect[j][1] < minCol) {
              minCol = coincideRect[j][1]
            }
            if (coincideRect[j][2] > maxRow) {
              maxRow = coincideRect[j][2]
            }
            if (coincideRect[j][3] > maxCol) {
              maxCol = coincideRect[j][3]
            }
          }
          this.mergedCell = nonCoincideRect
        }
      }
      this.mergedCell.push([minRow, minCol, maxRow, maxCol])
    },
    cancleDetail() {
      this.dialogFormVisible = false
      this.selectCells = []
      this.clearSelectCellStyle()
    }

  }
}
</script>
